package com.github.chirspan.xaas.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.chirspan.xaas.mybatis.service.impl.BaseServiceImpl;
import com.github.chirspan.xaas.rbac.dao.RbacUserDao;
import com.github.chirspan.xaas.rbac.model.RbacUser;
import com.github.chirspan.xaas.rbac.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ************************
 * <p></p>
 * *************************
 *
 * @author chenpan
 * @date 2021/1/19 14:33
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<RbacUserDao, RbacUser> implements IUserService {

    @Autowired
    private RbacUserDao rbacUserDao;

    @Override
    public RbacUser findUser(String username) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.apply("lower(username) = {0}", username.toLowerCase());
        return super.getOne(wrapper);
    }

    @Override
    public void updatePassword(String userName, String newPass) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", userName);
        RbacUser user = new RbacUser();
        user.setPassword(BCrypt.hashpw(newPass, BCrypt.gensalt()));
        super.update(user, wrapper);
    }

    @Override
    public void updateUserProfile(RbacUser user) {
        user.setUsername(null);
        user.setPassword(null);
        user.setUpdateTime(new Date());

        this.updateNotNull(user);
    }
}
